package com.ali.pogo;

import com.ali.sqlSession.SqlSession;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

public class MapperProxy<T> implements InvocationHandler, Serializable {
    private SqlSession sqlSession;
    private Class<T> mapperInterface;
    private Map<Method,MapperMethod> methodCache;

    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MapperMethod mapperMethod = this.cacheMapperMethod(method);
        return mapperMethod.execute(this.sqlSession,args);
    }

    private MapperMethod cacheMapperMethod(Method method) {
        MapperMethod mapperMethod = this.methodCache.get(method);
        if (mapperMethod == null){
            mapperMethod = new MapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration());
            this.methodCache.put(method,mapperMethod);
        }
        return mapperMethod;
    }
}
